package cn.tedu._06article.controller;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.ArticleInsertParam;
import cn.tedu._06article.pojo.dto.UserLoginParam;
import cn.tedu._06article.pojo.entity.Article;
import cn.tedu._06article.pojo.vo.ArticleVO;
import cn.tedu._06article.pojo.vo.UserSelectVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Validated
@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Api("01.用户管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam"+userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserSelectVO userSelectVO=userMapper.select(username,password);
        if (userSelectVO == null){
            return new JsonResult(StatusCode.USER_PASSWORD_ERROR);
        }
        session.setAttribute("user",userSelectVO);
        return JsonResult.ok(userSelectVO);
    }
    //发表文章
    @PostMapping("article")
    @ApiOperation("发表文章")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@RequestBody @Validated ArticleInsertParam articleInsertParam ,@ApiIgnore HttpSession session){
        UserSelectVO  userSelectVO= (UserSelectVO)session.getAttribute("user");
//        if (userSelectVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        //在filter里面去验证用户登录状态
        Article article = new Article();
        BeanUtils.copyProperties(articleInsertParam ,article);
        article.setUserId(userSelectVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }
    @GetMapping("selectByArticleId")
    @ApiOperation("查看指定文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章ID要求在1-100之间") @RequestParam Integer id){
        ArticleVO articleVO= (ArticleVO)userMapper.selectById(id);
        return JsonResult.ok(articleVO);
    }
}
























